<?php
//
// +------------------------------------------------------------------------+
// | Gecko Framework                                                        |
// +------------------------------------------------------------------------+
//
require_once( 'Gecko/DataGrid/Formatter/Table.php' );

/**
 * Advanced formatter that adds a View/Edit/Delete link
 * at the end of the table
 *
 * @package Gecko.DataGrid.Formatter;
 * @author Christopher Valderrama <valderrama.christopher@gmail.com>
 * @copyright Copyright (c) 2008
 * @version $Id$v1.0$ 2008
 * @access public
 **/
class Gecko_DataGrid_Formatter_ViewEditDeleteTable extends Gecko_DataGrid_Formatter_Table {
	/**
	 * The Column that contains the key
	 * to add to the link
	 *
	 * @var string
	 */
	private $idColumn;
	/**
	 * The Settings array
	 *
	 * @var array
	 */
	private $settings = array();

	/**
	 * Creates a new instance of the formatter,
	 * it needs a settings array and the name
	 * of the id column
	 *
	 * @param array The settings
	 * @param string The column name
	 */
	public function __construct($settings, $idColumn) {
		$this->idColumn = $idColumn;
		$this->settings = $settings;
	}

	/**
	 * Returns if a row is valid to add the links
	 */
	protected function isValidRow() {
		return true;
	}

	/**
	 * Called when row ends
	 */
	public function endRow() {
		if( $this->rowNum === 'header' ) {
			$span = 0;
			if( $this->settings['viewLink'] == true ) $span++;
			if( $this->settings['editLink'] == true ) $span++;
			if( $this->settings['deleteLink'] == true ) $span++;

			if( $span > 0 ) {
				$this->table->addHeader( $this->settings['header'], array( "colspan" => $span ) );
			}
		} else {
			if( !$this->isValidRow() ) {
				return;
			}
			$data = $this->grid->getDataSource()->getRowAt($this->rowNum);
			$key = $data[$this->idColumn];
			if(!$key) {
				throw new Gecko_DataGrid_Exception("{$this->idColumn} not found in data source");
			}

			$uri = sprintf( $this->uri, $key );

			if( $this->settings['viewLink'] == true ) {
				$viewLabel = (!empty($this->settings['viewLabel']) ? $this->settings['viewLabel'] : 'View' );
				$viewLink = $this->settings['viewUri'];
				$view = Gecko_HTML::LinkTag( $viewLabel, str_replace( "%VALUE%", $key, $viewLink ) );
				$this->table->addCell( $view );
			}
			if( $this->settings['editLink'] == true ) {
				$editLabel = (!empty($this->settings['editLabel']) ? $this->settings['editLabel'] : 'Edit' );
				$editLink = $this->settings['editUri'];
				$edit = Gecko_HTML::LinkTag( $editLabel, str_replace( "%VALUE%", $key, $editLink ) );
				$this->table->addCell( $edit );
			}
			if( $this->settings['deleteLink'] == true ) {
				$deleteLabel = (!empty($this->settings['deleteLabel']) ? $this->settings['deleteLabel'] : 'Delete' );
				$deleteLink = $this->settings['deleteUri'];
				$edit = Gecko_HTML::LinkTag( $deleteLabel, str_replace( "%VALUE%", $key, $deleteLink ) );
				$this->table->addCell( $delete );
			}
		}
	}
}
?>